/*******************************************************************************
 * Package: com.song.boot.springstudy.netty.ws
 * Type:    WebSocketServer
 * Date:    2023-06-24 17:29
 *
 * Copyright (c) 2023 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.boot.springstudy.netty.websocket.ws;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * 功能描述：webSocket 服务器
 *
 *
 * @author Songxianyang
 * @date 2023-06-24 17:29
 */
public class WebSocketServer {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossEvent = new NioEventLoopGroup(1);
        EventLoopGroup workerEvent = new NioEventLoopGroup();

        try {
            // 服务器端 配置参数
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossEvent,workerEvent) // 设置两个线程组
                    .channel(NioServerSocketChannel.class) // nio实现类通道
                    .option(ChannelOption.SO_BACKLOG,128) // 设置线程队列
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {  // workerEvent
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // 获取http解码器
                            pipeline.addLast("获取http解码器",new HttpServerCodec());
                            // 分块传输
                            pipeline.addLast(new ChunkedWriteHandler());
                            // http 协议 分段传输 减少服务器压力
                            //HttpObjectAggregator 可以将多个段聚合起来
                            //当浏览器发送大量数据时，就会发出多次http请求
                            pipeline.addLast(new HttpObjectAggregator(8091));
                            /**
                             * 将http协议升级为ws协议，保持长连接
                             * 传输方式为：帧
                             * 浏览器请求时 ws://localhost:7000/song 表示请求的uri
                             * 状态码为101
                             *
                             */
                            pipeline.addLast(new WebSocketServerProtocolHandler("/song"));
                            pipeline.addLast(new WebSocketServerHandler());// 向管道追加一个处理器
                        }
                    });// 给workerGroup的EventLoop对应的管道设置处理器
            System.out.println("服务器端启动完成！");
            ChannelFuture cf = serverBootstrap.bind(7000).sync(); // 绑定端口，并且同步，生成了一个ChannelFuture对象

            // 注册监听器 到 ChannelFuture。从而获取 异步回调
            cf.addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    System.out.println("监听成功：：：》》》》7000");
                }else {
                    System.out.println("监听失败");
                }
            });

            cf.channel().closeFuture().sync(); // 对关闭通道进行见监听
        } finally {
            bossEvent.shutdownGracefully();  // 关闭
            workerEvent.shutdownGracefully();
        }
    }

}
